<?php

namespace app\common\service;

use app\common\model\Permission as PermissionModel;
use app\common\tool\Tree;
use think\Db;
use think\Exception;

class Permission
{
    public function getList($page,$pageSize,$keywords){
        $start = ($page-1)*$pageSize;
        $where = [];
        if(!empty($keywords)){
            $where['name'] = ['like',"%".$keywords."%"];
        }
        $result = PermissionModel::where($where)->limit($start,$pageSize)->select();
        $total = PermissionModel::where($where)->count();
        return ['total'=>$total,'data'=>$result];
    }


    public function save($data){
        if($data['pid'] != 0){
            $parent = Db::table("permission")->where(['id'=>$data['pid']])->find();
            if(!$parent){
                throw new Exception("上级权限不正确");
            }
            $data['level'] = $parent['level'] + 1;
        }else{
            $data['level'] = 1;
        }
        return Db::table("permission")->insertGetId($data);
    }

    public function read($id){
        return Db::table("permission")->where(['id'=>$id])->find();
    }

    public function update($data,$id){
        return Db::table("permission")->where(['id'=>$id])->update($data);
    }

    public function delete($id){
        return Db::table("permission")->where(['id'=>$id])->delete();
    }

    public function tree(){
        $permissions = PermissionModel::where([])->select();
        $tree = new Tree($permissions,'id','pid');
        return $tree->getTree();
    }
}
